package org.ls.petclinic.web;

import cn.hutool.core.util.ObjectUtil;
import com.google.gson.Gson;
import org.ls.petclinic.dao.OwnerDao;
import org.ls.petclinic.dao.PetsDao;
import org.ls.petclinic.dao.TypeDao;
import org.ls.petclinic.dao.impl.OwnerDaoImpl;
import org.ls.petclinic.dao.impl.PetsDaoImpl;
import org.ls.petclinic.dao.impl.TypeDaoImpl;
import org.ls.petclinic.pojo.*;
import org.ls.petclinic.pojo.vo.PetsVo;
import org.ls.petclinic.pojo.vo.VetsVo;
import org.ls.petclinic.untils.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 浪矢先生
 * @description
 * @create 2022-12-05 22:10
 */
@WebServlet(urlPatterns = "/getPets")
public class GetPets extends BaseServlet {
    private PetsDao petsDao = new PetsDaoImpl();
    private OwnerDao ownerDao = new OwnerDaoImpl();
    private TypeDao typeDao = new TypeDaoImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Gson gson = new Gson();
        List<PetsVo> result = null;
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        String petName = req.getParameter("petName");
        String ownerName = req.getParameter("ownerName");
        List<Pets> pets = new ArrayList<>();
        if (!ObjectUtil.isNull(petName)) {
            pets = petsDao.getByName(petName);
        } else if (!ObjectUtil.isNull(ownerName)) {
            // 通过ownerName查找宠物信息
            List<Owner> byName = ownerDao.getByName(ownerName);
            for (Owner owner : byName) {
                List<Pets> byOwnerId = petsDao.getByOwnerId(owner.getId());
                pets.addAll(byOwnerId);
            }
        } else {
            pets = petsDao.getAll();
        }
        result = getOwner(pets);
        JdbcUtils.commitAndClose();
        resp.getWriter().write(String.valueOf(gson.toJson(result)));
    }

    /**
     * 获得宠物主人信息
     */
    private ArrayList<PetsVo> getOwner(List<Pets> pets) {
        ArrayList<PetsVo> petsVos = new ArrayList<>();
        for (Pets pet : pets) {
            Owner owner = ownerDao.getById(pet.getOwnerId());
            Type type = typeDao.getById(pet.getTypeId());
            PetsVo petsVo = new PetsVo(pet.getId(), pet.getName(), pet.getBirthDate(), owner, type);
            petsVos.add(petsVo);
        }
        return petsVos;
    }
}

